<?php

namespace app\crontab\controller;
use app\common\logic\Queue;
use app\common\model\Commission;
use app\common\model\Order;
use app\common\model\Platdataopen;
use ordersync\OrderSync;
use think\Cache;
use think\Db;

class Minutes extends BaseCron {


    /**
     * 默认方法
     */
    public function index() {

        // 订单佣金结算
        // $this->_commission_settle();

        // $this->_cron_queue();       // 邮件信息发送队列的处理
        // $this->_cron_common();      // 执行通用任务
        // $this->_cron_mail_send();   // 发送邮件消息
        $this->_cron_pintuan();        //拼团相关处理
//        $this->_order_platdata_gen();   // 179号文推送报文整理
//        $this->_order_platdata_upload();   // 179号文推送订单数据
//        $this->_order_allinpay_sync();   // 通联 支付单推送
//        $this->_order_wms_sync();   // WMS 订单同步
//        $this->_order_wms_query();   // WMS 订单状态同步
//        $this->_order_customs_sync();   // 关务订单同步
//        $this->_order_customs_query();   // 单一窗口 申报状态回执
//        $this->_order_customs_download();   // 单一窗口 申报回执下载
    }


    /**
     * 佣金结算
     */
    private function _commission_settle() {
        try {
            $commission_model = new Commission();
            $order_logic = new \app\common\logic\Order();
            // 查询订单
            $list = $commission_model->where([
                'state' => COMMISSION_STATE_ACTIVE, // 待结算
            ])->order('id asc')->limit(20)->select();

            if(!$list) return;

            foreach ($list as $item) {
                $order_logic->settleOrderCommission($item);
            }
            // 递归计算
            $this->_commission_settle();
        } catch (\Exception $e) {
            $this->log('_commission_settle Error' . $e->getMessage());
        }
    }

    /**
     *  179号文推送订单报文整理
     */
    private function _order_platdata_gen() {

        $list = Db::name('platdataopen')->where(['upload_state' => PLATDATA_STATE_NEW])->order('id desc')->limit(10)->select();

        if(!$list) return;

        $orderModel = new Order();

        foreach ($list as $key => $item) {
            // 查询订单
            $item['order_info'] = $orderModel->getOrderInfo([
                'order_sn' => $item['order_no'],
            ], ['order_common','order_goods']);

            if(!$item['order_info']) continue;
            $item['pay_info'] = Db::name('orderpay')->where(['pay_sn' => $item['order_info']['pay_sn']])->find();
            $orderModel->genPlatUploadData($item);
        }
    }

    /**
     *  179号文推送订单数据
     */
    private function _order_platdata_upload() {

        $list = Platdataopen::where(['upload_state' => PLATDATA_STATE_NOT_ISSUED])->order('id desc')->limit(10)->select();

        if(!$list) return;

        foreach ($list as $key => $item) {
            try {
                $request = OrderSync::PlatDataUpload($item);
                $request->getResponse();

                // 下发成功
                $item->save([
                    'upload_msg' => '',
                    'upload_state' => PLATDATA_STATE_ISSUED,
                    'update_time' => time(),
                ]);
            } catch (\Exception $e) {
                // 下发成功
               $item->save([
                    'upload_msg' => $e->getMessage(),
                    'upload_state' => PLATDATA_STATE_FAIL,
                    'update_time' => time(),
                ]);
            }
        }
    }

    /**
     *  通联 支付单推送
     */
    private function _order_allinpay_sync() {
        $orderModel = new Order();
        // 查询订单
        $list = $orderModel->getOrderList([
            'trade_mode' => ['in', config('trade_not_internal')],
            'order_state' => ['in', config('order_paid_states')],
            'allinpay_state' => ALLINPAY_STATE_NOT_ISSUED,
        ], 10, '*', 'order_id asc', 1, ['order_common','order_goods']);

        foreach ($list as $order) {
            if(!$order['trade_no']) {
                // 无需推送
                $orderModel->editOrder(['allinpay_state' => ALLINPAY_STATE_NULL], ['order_id' => $order['order_id']]);
                continue;
            }

            try {
                $request = OrderSync::AllinpaySync($order);
                $request->getResponse();

                // 下发成功
                (new Order())->editOrder([
                    'allinpay_msg' => '',
                    'allinpay_state' => ALLINPAY_STATE_ISSUED,
                    'allinpay_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            } catch (\Exception $e) {
                // 下发失败标记
                (new Order())->editOrder([
                    'allinpay_msg' => $e->getMessage(),
                    'allinpay_state' => ALLINPAY_STATE_FAIL,
                    'allinpay_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            }
        }
    }

    /**
     * WMS 订单同步
     */
    private function _order_wms_sync() {
        $orderModel = new Order();
        // 查询订单
        $list = $orderModel->getOrderList([
            'trade_mode' => ['in', config('trade_not_internal')],
            'order_state' => ['in', config('order_paid_states')],
            'customs_state' => CUSTOMS_STATE_SUCCESS,
            'wms_state' => WMS_STATE_NOT_ISSUED,
        ], 1, '*', 'order_id asc', 1, ['order_common','order_goods']);

        foreach ($list as $order) {
            try {
                $request = OrderSync::WMSSync($order);
                $request->getResponse();

                // 下发成功
                (new Order())->editOrder([
                    'wms_msg' => '',
                    'wms_state' => WMS_STATE_ISSUED,
                    'wms_update_time' => time(),
                    'wms_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            } catch (\Exception $e) {
                // 下发失败标记
                (new Order())->editOrder([
                    'wms_msg' => $e->getMessage(),
                    'wms_state' => WMS_STATE_FAIL,
                    'wms_update_time' => time(),
                    'wms_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            }
        }
    }

    /**
     * 关务订单状态获取
     */
    private function _order_wms_query() {
        $orderModel = new Order();
        $logic_order = new \app\common\logic\Order();
        // 查询订单
        $list = $orderModel->getOrderList([
            'trade_mode' => ['in', config('trade_not_internal')],
            'order_state' => ['in', config('order_paid_states')],
            'wms_state' => ['in', [WMS_STATE_ISSUED, WMS_STATE_QUERY]],
//            'wms_update_time' => ['elt', time() - 2 * 3600]     // 2小时查询一次
            'wms_update_time' => ['elt', time() - 1]     // 2小时查询一次
        ], 10, '*', 'order_id asc', 1, ['order_common','order_goods']);

        foreach ($list as $order_info) {
            try {
                $request = OrderSync::WMSQuery($order_info);
                $result = $request->getResponse();

                if($result['Status'] == 1 && isset($result['DeclformReturnInfo']) && isset($result['DeclformReturnInfo']['LogisticsNo']) && $result['DeclformReturnInfo']['LogisticsNo']) {
                    // 记录运单号
                    $post = array(
                        'reciver_name' => $order_info['extend_order_common']['reciver_name'],
                        'reciver_info' => serialize($order_info['extend_order_common']['reciver_info']),
                        'deliver_explain' => $order_info['extend_order_common']['deliver_explain'],
                        'daddress_id' => $order_info['extend_order_common']['daddress_id'],
                        'shipping_express_id' => 0,
                        'shipping_code' => $result['DeclformReturnInfo']['LogisticsNo'],
                    );
                    $logic_order->changeOrderSend($order_info, 'admin', session('member_name'), $post);
                    (new Order())->editOrder([
                        'wms_msg' => $result['Remark'],
                        'wms_state' => WMS_STATE_SEND,
                        'wms_update_time' => time(),
                    ], ['order_id' => $order_info['order_id']]);
                } else {
                    (new Order())->editOrder([
                        'wms_msg' => $result['Remark'],
                        'wms_state' => WMS_STATE_QUERY,     // 标记为查询中
                        'wms_update_time' => time(),
                    ], ['order_id' => $order_info['order_id']]);
                }
            } catch (\Exception $e) {
                // 查询失败标记
                (new Order())->editOrder([
                    'wms_msg' => $e->getMessage(),
                    'wms_state' => WMS_STATE_QUERY,         // 标记为查询中
                    'wms_update_time' => time(),
                ], ['order_id' => $order_info['order_id']]);
            }
        }
    }

    /**
     * 关务订单同步
     */
    private function _order_customs_sync() {
        $orderModel = new Order();
        // 查询订单
        $list = $orderModel->getOrderList([
            'trade_mode' => ['in', config('trade_not_internal')],
            'order_state' => ['in', config('order_paid_states')],
            'customs_state' => CUSTOMS_STATE_NOT_ISSUED,
        ], 10, '*', 'order_id asc', 10, ['order_common','order_goods']);

        foreach ($list as $order) {
            try {
                $request = OrderSync::CustomsSync($order);
                $request->getResponse();
                // 下发成功
                (new Order())->editOrder([
                    'customs_msg' => '',
                    'customs_state' => CUSTOMS_STATE_ISSUED,
                    'customs_update_time' => time(),
                    'customs_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            } catch (\Exception $e) {
                // 下发失败标记
                (new Order())->editOrder([
                    'customs_msg' => $e->getMessage(),
                    'customs_state' => CUSTOMS_STATE_FAIL,
                    'customs_update_time' => time(),
                    'customs_send_time' => time(),
                ], ['order_id' => $order['order_id']]);
            }
        }
    }

    /**
     * 单一窗口申报回执列表下载
     */
    private function _order_customs_query() {
        try {
            // 查询是否继续下载列表
            $check = Db::name('declare_download')->where([
                'state' => 0,
            ])->find();
            if($check) return;  // 回执获取完之后，再继续下载列表

            $list = OrderSync::CustomsQuery();

            $list = array_map(function ($val) {
                return [
                    'file_temp_id' => $val['fileTempID'],
                    'file_name' => $val['fileFullName'],
                    'upload_time' => strtotime($val['fileCreateDateTime']),
                    'update_time' => time(),
                    'create_time' => time()
                ];
            }, $list);
            Db::name('declare_download')->insertAll($list);
        }catch (\Exception $e) {
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }

    /**
     * 单一窗口 申报回执下载
     */
    private function _order_customs_download() {
        // 查询下载列表
        $list = Db::name('declare_download')->where([
            'state' => 0,
        ])->limit(10)->select();

        foreach ($list as $item) {
            try {
                $this->_order_customs_download_one($item);
            } catch (\Exception $e) {
                dump($e->getMessage());
            }
        }
    }

    /**
     * 单一窗口 申报回执下载（单文件）
     */
    private function _order_customs_download_one($item) {
        try {
            $result = OrderSync::CustomsDownloadOneFile($item);
            foreach($result as $xml) {
                $orderSn = preg_replace('/\.xml$/', '', $xml->FILE_ORIGINAL_NAME);
                if(empty($xml->ERROR_INFO)) {
                    if(!empty($xml->OrderReturn)) {
                        $orderSn = $xml->OrderReturn->orderNo;
                        // 申报回执
                        if($xml->OrderReturn->returnStatus == 2) {
                            // 申报成功
                            $errorMsg = $xml->OrderReturn->returnInfo;
                            $customsState = CUSTOMS_STATE_SUCCESS;
                        } elseif ($xml->OrderReturn->returnStatus < 0 || $xml->OrderReturn->returnStatus == 100) {
                            // 100 清单中的原产地与订单不一致 (不知道是否为专属错误代码)
                            // 申报失败
                            $errorMsg = $xml->OrderReturn->returnInfo;
                            $customsState = CUSTOMS_STATE_FAIL;
                        } else {
                            // 不知道还有没有其他状态，直接跳过不做处理
                            continue;
                        }
                    } else {
                        // 下发回执
                        $errorMsg = '';
                        $customsState = CUSTOMS_STATE_ISSUE_SUCCESS;
                    }
                } else {
                    $errorMsg = implode('|', (array)$xml->ERROR_INFO);
                    $customsState = CUSTOMS_STATE_FAIL;
                }

                // 回执标记
                (new Order())->editOrder([
                    'customs_msg' => $errorMsg,
                    'customs_state' => $customsState,
                    'customs_update_time' => time(),
                ], ['order_sn' => $orderSn]);
            }

            // 文件标记已下载
            Db::name('declare_download')->where([
                'id' => $item['id'],
            ])->update([
                'state' => 1,
            ]);

        } catch (\Exception $e) {
            dump($e->getMessage());
        }
    }

    /**
     * 邮件信息发送队列的处理
     */
    private function _cron_queue(){
        //获取当前存储的数量
        $QueueClientNum = Cache::get('QueueClientNum');
        $QueueLogic = new Queue();
        for($i=1;$i<=$QueueClientNum;$i++){
            $info = Cache::pull('QueueClient_'.$i);#获取缓存
            if(empty($info)){
                continue;
            }
            $info = unserialize($info);
            $key = key($info);
            $value = current($info);
            $QueueLogic->$key($value);
        }
        Cache::set('QueueClientNum',NULL);
    }


    /**
     * 拼团相关处理
     */
    private function _cron_pintuan()
    {
        $ppintuan_model = model('ppintuan',"common\model");
        $ppintuangroup_model = model('ppintuangroup',"common\model");
        $ppintuanorder_model = model('ppintuanorder',"common\model");
        //自动关闭时间过期的店铺拼团活动
        $condition = array();
        $condition['pintuan_end_time'] = array('lt',TIMESTAMP);
        $ppintuan_model->endPintuan($condition);


        //查看正在进行开团的列表.
        $condition = array();
        $condition['pintuangroup_state'] = 1;
        $pintuangroup_list = $ppintuangroup_model->getPpintuangroupList($condition);

        $success_ids = array();#拼团开团成功的拼团开团ID
        $fail_ids = array();#拼团开团失败的拼团开团ID
        foreach ($pintuangroup_list as $key => $pintuangroup) {

            //判断当前参团是否已过期
            if(TIMESTAMP >= $pintuangroup['pintuangroup_starttime'] + $pintuangroup['pintuangroup_limit_hour']*3600){

                //当已参团人数  大于 当前开团的  参团人数
                if($pintuangroup['pintuangroup_joined']>=$pintuangroup['pintuangroup_limit_number']){

                    //满足开团人数,查看对应的订单是否付款,未付款则拼团失败,订单取消,订单款项退回.
                    $condition = array();
                    $condition['ppintuanorder.pintuangroup_id'] = $pintuangroup['pintuangroup_id'];
                    $condition['order.order_state'] = 20;
                    $count = db('ppintuanorder')->alias('ppintuanorder')->join('__ORDER__ order','order.order_id=ppintuanorder.order_id')->where($condition)->count();
                    if($count == $pintuangroup['pintuangroup_joined']){
                        //表示全部付款,拼团成功
                        $success_ids[] = $pintuangroup['pintuangroup_id'];
                    }else{
                        $fail_ids[] = $pintuangroup['pintuangroup_id'];
                    }
                }else{
                    //未满足开团人数
                    $fail_ids[] = $pintuangroup['pintuangroup_id'];
                }
            }
        }

        $condition = array();
        //在拼团失败的所有订单，已经付款的订单列表，取消订单,并且退款，未付款的订单自动取消订单
        $condition['ppintuanorder.pintuangroup_id'] = array('in', implode(',', $fail_ids));
        $ppintuanorder_list = db('ppintuanorder')->field('order.*')->alias('ppintuanorder')->join('__ORDER__ order','order.order_id=ppintuanorder.order_id')->where($condition)->select();

        //针对已付款,拼团没成功的订单,进行取消订单以及退款操作
        $order_model = model('order',"common\model");
        $logic_order = model('order','common\logic');

        foreach ($ppintuanorder_list as $key => $order_info) {
            $logic_order->changeOrderStateCancel($order_info,'system','系统','拼团未成功系统自动关闭订单',true,false,true);
        }

        //失败修改拼团相关数据库信息
        $condition = array();
        $condition['pintuangroup_id'] = array('in', implode(',', $fail_ids));
        $ppintuangroup_model->failPpintuangroup($condition);

        //成功修改拼团相关数据库信息
        $condition = array();
        $condition['pintuangroup_id'] = array('in', implode(',', $success_ids));
        $ppintuangroup_model->successPpintuangroup($condition);

    }


    /**
     * 发送邮件消息
     */
    private function _cron_mail_send() {
        //每次发送数量
        $_num = 50;
        $mailcron_model = model('mailcron');
        $cron_array = $mailcron_model->getMailCronList(array(), $_num);
        if (!empty($cron_array)) {
            $email = new \sendmsg\Email();
            $mail_array = array();
            foreach ($cron_array as $val) {
                $return = $email->send_sys_email($val['mailcron_address'],$val['mailcron_subject'],$val['mailcron_contnet']);
                if ($return) {
                    // 记录需要删除的id
                    $mail_array[] = $val['mailcron_id'];
                }
            }
            // 删除已发送的记录
            $mailcron_model->delMailCron(array('mailcron_id' => array('in', $mail_array)));
        }
    }

    /**
     * 执行通用任务
     */
    private function _cron_common(){

        //查找待执行任务
        $cron_model = model('cron');
        $cron = $cron_model->getCronList(array('exetime'=>array('elt',TIMESTAMP)));

        if (!is_array($cron)) return ;
        $cron_array = array(); $cronid = array();
        foreach ($cron as $v) {
            $cron_array[$v['type']][$v['exeid']] = $v;
        }
        foreach ($cron_array as $k=>$v) {
            // 如果方法不存是，直接删除id
            if (!method_exists($this,'_cron_'.$k)) {
                $tmp = current($v);
                $cronid[] = $tmp['id'];continue;
            }
            $result = call_user_func_array(array($this,'_cron_'.$k),array($v));
            if (is_array($result)){
                $cronid = array_merge($cronid,$result);
            }
        }
        //删除执行完成的cron信息
        if (!empty($cronid) && is_array($cronid)){
            $cron_model->delCron(array('id'=>array('in',$cronid)));
        }
    }

    /**
     * 上架
     *
     * @param array $cron
     */
    private function _cron_1($cron = array()){
        $condition = array('goods_commonid' => array('in',array_keys($cron)));
        $update = model('goods')->editProducesOnline($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    /**
     * 根据商品id更新商品促销价格
     *
     * @param array $cron
     */
    private function _cron_2($cron = array()){
        $condition = array('goods_id' => array('in',array_keys($cron)));
        $update = model('goods')->editGoodsPromotionPrice($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    /**
     * 优惠套装过期
     *
     * @param array $cron
     */
    private function _cron_3($cron = array()) {
        $cronid = array();
        return $cronid;
    }

    /**
     * 推荐展位过期
     *
     * @param array $cron
     */
    private function _cron_4($cron = array()) {
        $cronid = array();
        return $cronid;
    }

    /**
     * 抢购开始更新商品促销价格
     *
     * @param array $cron
     */
    private function _cron_5($cron = array()) {
        $condition = array();
        $condition['goods_commonid'] = array('in', array_keys($cron));
        $condition['groupbuy_starttime'] = array('lt', TIMESTAMP);
        $condition['groupbuy_endtime'] = array('gt', TIMESTAMP);
        $groupbuy = model('groupbuy')->getGroupbuyList($condition);
        foreach ($groupbuy as $val) {
            model('goods')->editGoods(array('goods_promotion_price' => $val['groupbuy_price'], 'goods_promotion_type' => 1), array('goods_commonid' => $val['goods_commonid']));
        }
        //返回执行成功的cronid
        $cronid = array();
        foreach ($cron as $v) {
            $cronid[] = $v['id'];
        }
        return $cronid;
    }

    /**
     * 抢购过期
     *
     * @param array $cron
     */
    private function _cron_6($cron = array()) {
        $condition = array('goods_commonid' => array('in', array_keys($cron)));
        //抢购活动过期
        $update = model('groupbuy')->editExpireGroupbuy($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    /**
     * 限时折扣过期
     *
     * @param array $cron
     */
    private function _cron_7($cron = array()) {
        $condition = array('xianshi_id' => array('in', array_keys($cron)));
        //限时折扣过期
        $update = model('pxianshi')->editExpireXianshi($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

}
?>
